﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using EFong.Data;

namespace EFong.Host
{
    public class ConnectionStringManager
    {
        const string FILENAME = "db";

        public static void SaveFile(ConnectionString connectionString)
        {
            using (FileStream fs = new FileStream(FILENAME, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                new BinaryFormatter().Serialize(fs, connectionString);
            }
        }

        public static ConnectionString LoadByFile()
        {
            try
            {
                using (FileStream fs = new FileStream(FILENAME, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    return (ConnectionString)formatter.Deserialize(fs);
                }
            }
            catch (FileNotFoundException)
            {
                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void SetConnectionString(ConnectionString connectionString) 
        {
            string cs = string.Format(@"metadata=res://*/EFongModel.csdl|res://*/EFongModel.ssdl|res://*/EFongModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};MultipleActiveResultSets=True'",
                                        connectionString.DataSource, connectionString.InitialCatalog, connectionString.UserID, connectionString.Password);

            EFongEntitiesManager.SetConntectionString(cs);
        }

        public void TestSave()
        {
            ConnectionString connectionString = new ConnectionString()
            {
                DataSource = "Anson-Notebook",
                InitialCatalog = "EFong",
                UserID = "sa",
                Password = "123456"
            };

            SaveFile(connectionString);
        }


        public static void Test(ConnectionString connectionString)
        {
            string cs = string.Format(@"metadata=res://*/EFongModel.csdl|res://*/EFongModel.ssdl|res://*/EFongModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};MultipleActiveResultSets=True'",
                                        connectionString.DataSource, connectionString.InitialCatalog, connectionString.UserID, connectionString.Password);

            EFongEntitiesManager.Test(cs);
        }
    }
}
